﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Data;
using System.Collections;
using System.Data.SqlClient;
using System.Drawing;

namespace IEWebSite.Administration
{
    public partial class Conferinta : BaseListPage
    {
        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection sqlConnection = Utils.GetSqlConnection();
            sqlDataAdapter = new SqlDataAdapter("SELECT [IdConferinta],[Titlu],[Descriere],[TitluEN],[DescriereEN],[Logo],[LogoMimeType], '' AS Poza, [WebSite] FROM [CatedraIE].[dbo].[Conferinta]", sqlConnection);

            SqlCommand InsertCommand = new SqlCommand("INSERT INTO [Conferinta] ([" + GetKeyColumn() + "], [Titlu],[TitluEN],[Descriere],[DescriereEN],[Logo],[LogoMimeType],[WebSite]) VALUES (@" + GetKeyColumn() + ", @Titlu,@TitluEN,@Descriere,@DescriereEN,@Logo,@LogoMimeType, @WebSIte)", sqlConnection);
            InsertCommand.Parameters.Add(new SqlParameter(GetKeyColumn(), SqlDbType.Int, 4, GetKeyColumn()));
            InsertCommand.Parameters.Add(new SqlParameter("Titlu", SqlDbType.NVarChar, 200, "Titlu"));
            InsertCommand.Parameters.Add(new SqlParameter("TitluEN", SqlDbType.NVarChar, 200, "TitluEN"));
            InsertCommand.Parameters.Add(new SqlParameter("Descriere", SqlDbType.NVarChar, 2400, "Descriere"));
            InsertCommand.Parameters.Add(new SqlParameter("DescriereEN", SqlDbType.NVarChar, 2400, "DescriereEN"));
            InsertCommand.Parameters.Add(new SqlParameter("Logo", SqlDbType.VarBinary,-1,"Logo"));
            InsertCommand.Parameters.Add(new SqlParameter("LogoMimeType", SqlDbType.NVarChar, 100, "LogoMimeType"));
            InsertCommand.Parameters.Add(new SqlParameter("WebSite", SqlDbType.NVarChar, 150, "WebSite"));
           
            sqlDataAdapter.InsertCommand = InsertCommand;

            SqlCommand DeleteCommand = new SqlCommand("DELETE FROM Conferinta WHERE " + GetKeyColumn() + " = @" + GetKeyColumn(), sqlConnection);
            DeleteCommand.Parameters.Add(new SqlParameter(GetKeyColumn(), SqlDbType.Int, 4, GetKeyColumn()));
            sqlDataAdapter.DeleteCommand = DeleteCommand;

            SqlCommand UpdateCommand = new SqlCommand("UPDATE Conferinta SET Titlu = @Titlu, TitluEN = @TitluEn, Descriere = @Descriere, DescriereEN = @DescriereEN, Logo=@Logo,LogoMimeType = @LogoMimeType, WebSite=@WebSite WHERE " + GetKeyColumn() + " = @" + GetKeyColumn(), sqlConnection);
            UpdateCommand.Parameters.Add(new SqlParameter(GetKeyColumn(), SqlDbType.Int, 4, GetKeyColumn()));
            UpdateCommand.Parameters.Add(new SqlParameter("Titlu", SqlDbType.NVarChar, 200, "Titlu"));
            UpdateCommand.Parameters.Add(new SqlParameter("TitluEN", SqlDbType.NVarChar, 200, "TitluEN"));
            UpdateCommand.Parameters.Add(new SqlParameter("Descriere", SqlDbType.NVarChar, 2400, "Descriere"));
            UpdateCommand.Parameters.Add(new SqlParameter("DescriereEN", SqlDbType.NVarChar, 2400, "DescriereEN"));
            UpdateCommand.Parameters.Add(new SqlParameter("Logo", SqlDbType.VarBinary, -1, "Logo"));
            UpdateCommand.Parameters.Add(new SqlParameter("LogoMimeType", SqlDbType.NVarChar, 100, "LogoMimeType"));
            UpdateCommand.Parameters.Add(new SqlParameter("WebSite", SqlDbType.NVarChar, 150, "WebSite"));
            sqlDataAdapter.UpdateCommand = UpdateCommand;

            if (!Page.IsPostBack)
            {
                RadGrid1.DataSource = SessionTable;
                RadGrid1.DataBind();
            }
        }

        protected void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            DataRow newRow = this.SessionTable.NewRow();

            newRow["Titlu"] = (userControl.FindControl("txtTitlu") as TextBox).Text;
            newRow["Descriere"] = (userControl.FindControl("Descriere") as RadEditor).Text;
            newRow["TitluEN"] = (userControl.FindControl("txtTitluEN") as TextBox).Text;
            newRow["DescriereEN"] = (userControl.FindControl("DescriereEN") as RadEditor).Text;
            newRow["WebSite"] = (userControl.FindControl("txtWebsite") as TextBox).Text;
            FileUpload fileUpload = (userControl.FindControl("FileUpload1") as FileUpload);
            if (fileUpload.FileBytes.Length != 0)
            {
                //System.IO.BinaryReader bs = new System.IO.BinaryReader((userControl.FindControl("ruplFiles") as RadUpload).UploadedFiles[0].InputStream);
                //byte[] buffer;
                //buffer = bs.ReadBytes(Convert.ToInt32(bs.BaseStream.Length));
                //bs.Close();
                //(userControl.FindControl("ruplFiles") as RadUpload).UploadedFiles[0].InputStream.Close();
                //newRow["Logo"] = buffer;
                //(userControl.FindControl("ruplFiles") as RadUpload).UploadedFiles.Clear();
                newRow["Logo"] = fileUpload.FileBytes;
                newRow["LogoMimeType"] = (userControl.FindControl("FileUpload1") as FileUpload).PostedFile.ContentType;
             }

            newRow[GetKeyColumn()] = Utils.GetNextTableId(GetTableName());

            try
            {
                this.SessionTable.Rows.Add(newRow);
                this.sqlDataAdapter.Update(SessionTable);
                this.SessionTable.AcceptChanges();
            }
            catch (Exception ex)
            {
                Label lblError = new Label();
                lblError.Text = "Nu s-a putut realiza insertul. Motivul: " + ex.Message;
                lblError.ForeColor = System.Drawing.Color.Red;
                RadGrid1.Controls.Add(lblError);
                e.Canceled = true;
            }
        }

        protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            this.RadGrid1.DataSource = this.SessionTable;
        }

        protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            DataRow[] changedRows = this.SessionTable.Select(GetKeyColumn()+"= " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex][GetKeyColumn()]);

            if (changedRows.Length != 1)
            {
                RadGrid1.Controls.Add(new LiteralControl("Nu poate fi localizata conferinta pentru a fi modificata."));
                e.Canceled = true;
                return;
            }

            Hashtable newValues = new Hashtable();
            newValues["Titlu"] = (userControl.FindControl("txtTitlu") as TextBox).Text;
            newValues["Descriere"] = (userControl.FindControl("Descriere") as RadEditor).Text;
            newValues["TitluEN"] = (userControl.FindControl("txtTitluEN") as TextBox).Text;
            newValues["DescriereEN"] = (userControl.FindControl("DescriereEN") as RadEditor).Text;
            newValues["WebSite"] = (userControl.FindControl("txtWebsite") as TextBox).Text;
            FileUpload fileUpload = (userControl.FindControl("FileUpload1") as FileUpload);
            if (fileUpload.FileBytes.Length != 0)
            {
                //System.IO.BinaryReader bs = new System.IO.BinaryReader((userControl.FindControl("ruplFiles") as RadUpload).UploadedFiles[0].InputStream);
                //byte[] buffer;
                //buffer = bs.ReadBytes(Convert.ToInt32(bs.BaseStream.Length));
                //bs.Close();
                //(userControl.FindControl("ruplFiles") as RadUpload).UploadedFiles[0].InputStream.Close();
                //newRow["Logo"] = buffer;
                //(userControl.FindControl("ruplFiles") as RadUpload).UploadedFiles.Clear();
                newValues["Logo"] = fileUpload.FileBytes;
                newValues["LogoMimeType"] = (userControl.FindControl("FileUpload1") as FileUpload).PostedFile.ContentType;
            }
            
            changedRows[0].BeginEdit();
            try
            {
                foreach (DictionaryEntry entry in newValues)
                {
                    changedRows[0][(string)entry.Key] = entry.Value;
                }
                changedRows[0].EndEdit();
                this.sqlDataAdapter.Update(SessionTable);
                this.SessionTable.AcceptChanges();
            }
            catch (Exception ex)
            {
                changedRows[0].CancelEdit();

                Label lblError = new Label();
                lblError.Text = "Nu s-a putut realiza Upate-ul. Motivul: " + ex.Message;
                lblError.ForeColor = System.Drawing.Color.Red;
                RadGrid1.Controls.Add(lblError);

                e.Canceled = true;
            }
        }

        protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
        {
            string ID = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex][GetKeyColumn()].ToString();
            if (SessionTable.Rows.Find(ID) != null)
            {
                SessionTable.Rows.Find(ID).Delete();
                this.sqlDataAdapter.Update(SessionTable);
                SessionTable.AcceptChanges();
            }
        }
        #endregion

        protected override string GetTableName()
        {
            return "Conferinta";
        }

        /// <summary>
        /// Remove, Add, Customize Columns
        /// http://www.telerik.com/help/aspnet/grid/grdusingcolumns.html
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
        {
            if (e.Column.UniqueName.StartsWith("Id") || e.Column.UniqueName == "LogoMimeType")
            {
                GridBoundColumn boundColumn = e.Column as GridBoundColumn;
                boundColumn.Visible = false;
            }
            else if (e.Column.UniqueName == "Poza")
            {
                GridBoundColumn boundColumn = e.Column as GridBoundColumn;
                boundColumn.DataField = GetKeyColumn();
                boundColumn.DataFormatString = "<img src=\"DBFileDownloader.aspx?table=Conferinta&column=Logo&id={0:D}\" />";
            }
        }

           protected DataTable SessionTable
        {
            get
            {
                object obj = this.Session[GetTableName()];
                if ((!(obj == null)))
                {
                    return ((DataTable)(obj));
                }
                DataTable myDataTable = new DataTable();
                sqlDataAdapter.Fill(myDataTable);
                myDataTable.PrimaryKey = new DataColumn[] { myDataTable.Columns[GetKeyColumn()] };
                this.Session[GetTableName()] = myDataTable;
                myDataTable.AcceptChanges();
                return myDataTable;
            }
        }

           #region Attributes
           protected SqlDataAdapter sqlDataAdapter;
           #endregion
    }
}
